112. 路径总和
为保证权益,题目请参考 112. 路径总和(From LeetCode).
解决方案1
CPP
C++
#include <iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
explicit TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
class Solution {
public:
static bool hasPathSum(TreeNode *root, int sum) {
if (root == nullptr) {
return false;
} else {
sum -= root->val;
if(root->left == nullptr && root->right == nullptr){
return sum ==0;
}
if(root->left){
if(hasPathSum(root->left, sum)){
return true;
}
}
if(root->right){
if(hasPathSum(root->right, sum)){
return true;
}
}
return false;
}
}
};
int main() {
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44